package com.dave.weixin.common.tools;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.api.scripting.ScriptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import sun.rmi.runtime.Log;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by Dave on 2018/7/7
 * Describes
 */
@Component
public class RestComponent {
    @Autowired
    private RestTemplate restTemplate;

    public <T> T sendPost(String url, Object data, Class<T> target) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(data);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonStr, headers);

        System.out.println("url"+url);
        String resultStr = restTemplate.postForObject(url, formEntity, String.class);
        return mapper.readValue(resultStr, target);

    }
}
